// app/contexts/ShoppingContext.tsx
'use client'

import React, { createContext, useContext, useState, ReactNode, useEffect } from 'react'

// 定义产品类型
interface Product {
    id: number
    name: string
    price: number
    image: string
    category: string
}

// 定义购物车中的商品类型，包含数量
interface CartItem extends Product {
    quantity: number
}

// 定义购买记录中的商品类型，包含状态和购买日期
interface PurchaseItem extends Product {
    status: '未发货' | '已发货'
    purchaseDate: string // 使用字符串存储日期
}

// 定义上下文属性
interface ShoppingContextProps {
    cart: CartItem[]
    addToCart: (product: Product) => void
    removeFromCart: (productId: number) => void
    updateQuantity: (productId: number, quantity: number) => void
    checkout: () => void
    purchases: PurchaseItem[]
}

// 创建上下文
const ShoppingContext = createContext<ShoppingContextProps | undefined>(undefined)

// 创建自定义 hook 以便在组件中使用上下文
export const useShopping = () => {
    const context = useContext(ShoppingContext)
    if (!context) {
        throw new Error("useShopping 必须在 ShoppingProvider 内使用")
    }
    return context
}

// 创建提供者组件
export const ShoppingProvider = ({ children }: { children: ReactNode }) => {
    const [cart, setCart] = useState<CartItem[]>(() => {
        if (typeof window !== 'undefined') {
            const storedCart = localStorage.getItem('cart')
            return storedCart ? JSON.parse(storedCart) : []
        }
        return []
    })

    const [purchases, setPurchases] = useState<PurchaseItem[]>(() => {
        if (typeof window !== 'undefined') {
            const storedPurchases = localStorage.getItem('purchases')
            return storedPurchases ? JSON.parse(storedPurchases) : []
        }
        return []
    })

    // 使用 useEffect 以便在 cart 或 purchases 变化时更新 localStorage
    useEffect(() => {
        localStorage.setItem('cart', JSON.stringify(cart))
    }, [cart])

    useEffect(() => {
        localStorage.setItem('purchases', JSON.stringify(purchases))
    }, [purchases])

    // 添加商品到购物车
    const addToCart = (product: Product) => {
        setCart(prevCart => {
            const existingItem = prevCart.find(item => item.id === product.id)
            if (existingItem) {
                return prevCart.map(item =>
                    item.id === product.id ? { ...item, quantity: item.quantity + 1 } : item
                )
            } else {
                return [...prevCart, { ...product, quantity: 1 }]
            }
        })
    }

    // 从购物车中移除商品
    const removeFromCart = (productId: number) => {
        setCart(prevCart => prevCart.filter(item => item.id !== productId))
    }

    // 更新购物车中商品的数量
    const updateQuantity = (productId: number, quantity: number) => {
        setCart(prevCart =>
            prevCart.map(item =>
                item.id === productId ? { ...item, quantity: quantity < 1 ? 1 : quantity } : item
            )
        )
    }

    // 结算购物车
    const checkout = () => {
        const newPurchases: PurchaseItem[] = cart.map(item => ({
            ...item,
            status: '未发货',
            purchaseDate: new Date().toISOString(),
        }))
        setPurchases(prevPurchases => [...prevPurchases, ...newPurchases])
        setCart([])
    }

    return (
        <ShoppingContext.Provider value={{ cart, addToCart, removeFromCart, updateQuantity, checkout, purchases }}>
            {children}
        </ShoppingContext.Provider>
    )
}
